package com.service.impl;

import com.common.exception.db.DeleteException;
import com.common.exception.db.InsertException;
import com.common.exception.db.UpdateException;
import com.common.paging.PagingData;
import com.dao.ManageDao;
import com.dao.OrderDao;
import com.entity.*;
import com.service.ManageService;
import com.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/2/13 0013.
 */
@Service
public class ManageServiceImpl implements ManageService{
    @Autowired
    private ManageDao dao;
    @Autowired
    private OrderDao orderDao;

    @Override
    public PagingData findAdvicesList(Integer page, Integer length) {
        List<AdvicesInfo> list = dao.findAdvicesList(page, length);
        int count = dao.findAdvicesListCount();
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public int setAdvices(Integer id) {
        return dao.setAdvices(id);
    }

    @Override
    public List<Teacherinfo> findTeacherList(Integer page, Integer length, String search) {
        page = (page - 1) * 10;
        List<Teacherinfo> list = dao.findAll(page, length, search);
        for(Teacherinfo teacherinfo : list){
            List subjectName = dao.findSubjectName(teacherinfo.getUserId());
            teacherinfo.setSubject(subjectName);
        }
        return list;
    }

    @Override
    public int findCount(String search) {
        return dao.findCount(search);
    }

    @Override
    public PagingData findUserTypeList(Integer page, Integer length, String search) {
        page = (page - 1) * 10;
        List<LoginInfo> list = dao.findUserList(page, length, search);
        for (LoginInfo loginInfo : list) {
            int num = dao.findParentMyRelease(loginInfo.getId());
            if (num == 0) {
                loginInfo.setReleaseStatus("未发布");
            } else {
                loginInfo.setReleaseStatus("已发布");
            }
        }
        int count = dao.findUserListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public List<StudentInfo> houduanMyRelease(Integer userId) {
        List<StudentInfo> info = dao.houduanMyRelease(userId);
        for(StudentInfo studentInfo : info){
            List subjectName = dao.findSubjectName(studentInfo.getUserId());
            studentInfo.setSubjectInfo(subjectName);
        }
        return info;
    }

    @Override
    public PagingData findCertificationList(Integer page, Integer length, String search, Integer type) {
        List<CertificationInfo> list = dao.findCertificationList(page, length, search, type);
        int count = dao.findCertificationListCount(search, type);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    @Transactional
    public int setCertification(Integer id, Integer type,Integer pid) {
        int userId = dao.findUserId(id);
        String userType = dao.findUserType(userId);
        int count = dao.setCertification(id,type);
        if(count > 0){
            if(type == 1){
                if(pid != 0){
                    if(userType.equals("student")){
                        count = dao.updatePidMoney(pid);
                        if(count > 0){
                            String uuid = UUIDUtil.get32UUID();
                            BigDecimal a = new BigDecimal(20);
                            count = dao.insertBill(pid,uuid,a,1,"推广奖励");
                            if(count > 0){
                                count = dao.updatePromotionAcStatus(userId,pid);
                                if(count > 0){
                                    if(userType.equals("student")){
                                        BigDecimal m = new BigDecimal(50);
                                        count = dao.updateUserMoney(userId,m);
                                        if(count > 0){
                                            String uuids = UUIDUtil.get32UUID();
                                            count = dao.insertBill(userId,uuids,m,1,"认证奖励");
                                            if(count > 0){
                                                return count;
                                            }else{
                                                throw new UpdateException("新增流水失败");
                                            }
                                        }else{
                                            throw new UpdateException("认证通过给50失败");
                                        }
                                    }else{
                                        return count;
                                    }
                                }else {
                                    throw new UpdateException("修改认证状态失败");
                                }
                            }else{
                                throw new UpdateException("新增流水失败");
                            }
                        }else{
                            throw new UpdateException("修改失败");
                        }
                    }else{
                        count = dao.updatePromotionAcStatus(userId,pid);
                        if(count > 0){
                            if(userType.equals("student")){
                                BigDecimal m = new BigDecimal(50);
                                count = dao.updateUserMoney(userId,m);
                                if(count > 0){
                                    String uuids = UUIDUtil.get32UUID();
                                    count = dao.insertBill(userId,uuids,m,1,"认证奖励");
                                    if(count > 0){
                                        return count;
                                    }else{
                                        throw new UpdateException("新增流水失败");
                                    }
                                }else{
                                    throw new UpdateException("认证通过给50失败");
                                }
                            }else{
                                return count;
                            }
                        }else {
                            throw new UpdateException("修改认证状态失败");
                        }
                    }

                }else{
                    if(userType.equals("student")){
                        BigDecimal m = new BigDecimal(50);
                        count = dao.updateUserMoney(userId,m);
                        if(count > 0){
                            String uuids = UUIDUtil.get32UUID();
                            count = dao.insertBill(userId,uuids,m,1,"认证奖励");
                            if(count > 0){
                                return count;
                            }else{
                                throw new UpdateException("新增流水失败");
                            }
                        }else{
                            throw new UpdateException("认证通过给50失败");
                        }
                    }else{
                        return count;
                    }
                }
            }else {
                return count;
            }
        }else {
            throw new UpdateException("修改失败");
        }
    }

    @Override
    public PagingData findUserBillList(Integer page, Integer length, String search) {
        List<BillInfo> list = dao.findUserBillList(page, length, search);
        int count = dao.findUserBillListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public PagingData findTeacherValueList(Integer page, Integer length, String search) {
        List<Teacherinfo> list = dao.findTeacherValueList(page, length, search);
        int count = dao.findTeacherValueListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public int setTeacherValue(Integer value, Integer id) {
        return dao.setTeacherValue(value,id);
    }

    @Override
    public PagingData findRewardList(Integer page, Integer length, String search) {
        List<HRewardInfo> list = dao.findRewardList(page,length,search);
        int count = dao.findRewardListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public PagingData findShareList(Integer page, Integer length, String search) {
        List<HShareInfo> list = dao.findShareList(page,length,search);
        int count = dao.findShareListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public Map findUserType() {
        int a = dao.findUserType1();
        int b = dao.findUserType2();
        Map map = new HashMap();
        map.put("student", a);
        map.put("teacher", b);
        return map;
    }

    @Override
    public PagingData findMidwayRefund(Integer page, Integer length, String search) {
        List<HRecordInfo> list = dao.findMidwayRefund(page,length,search);
        int count = dao.findMidwayRefundCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public PagingData findRefundRecordList(Integer page, Integer length, String search) {
        List<HRecordInfo> list = dao.findRefundRecordList(page,length,search);
        int count = dao.findRefundRecordListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public PagingData findTransactionList(Integer page, Integer length, String search) {
        List<HRecordInfo1> list = dao.findTransactionList(page,length,search);
        int count = dao.findTransactionListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public PagingData findTeacherMoneyList(Integer page, Integer length, String search) {
        List<HTeacherInfo> list = dao.findTeacherMoneyList(page,length,search);
        int count = dao.findTeacherMoneyListCount(search);
        PagingData pagingData = new PagingData();
        pagingData.setData(list);
        pagingData.setRecordsTotal(count);
        return pagingData;
    }

    @Override
    public int resetTeacherMoney(Integer userId,BigDecimal lyMoney) {
        int count = dao.findIfMoneyIsSame(userId,lyMoney);
        if(count > 0){
            count = dao.resetTeacherMoney(userId);
            if(count > 0){
                return count;
            }else{
                return 0;
            }
        }else{
            return -1;
        }
    }

    @Override
    @Transactional
    public int deleteRefundRecord(Integer id) {
        int recordId = dao.findRecordId(id);
        int count = dao.deleteRefundRecord(id);
        if(count > 0){
            count = orderDao.deleteOrder(recordId);
            if(count > 0){
                return count;
            }else{
                throw new DeleteException("删除失败");
            }
        }else {
            throw new DeleteException("删除失败");
        }
    }

    @Override
    public List findStatistics() {
        List list = new ArrayList();
        int a1 = 0 ;
        int a2 = 0 ;
        int a3 = 0 ;
        int a4 = 0 ;
        int a5 = 0 ;
        int a6 = 0 ;
        int a7 = 0 ;
        int a8 = 0 ;
        int a9 = 0 ;
        int a10 = 0 ;
        int a11 = 0 ;
        int a12 = 0 ;
        List<Date> aa = dao.findStatistics();
        Calendar cal = Calendar.getInstance();
        for(Date date : aa){
            cal.setTime(date);
            int month = cal.get(Calendar.MONTH )+1; //注意月份是从0开始的,比如当前7月，获得的month为6
            if(month == 1){
                a1++;
            }else if(month == 2){
                a2++;
            }else if(month == 3){
                a3++;
            }else if(month == 4){
                a4++;
            }else if(month == 5){
                a5++;
            }else if(month == 6){
                a6++;
            }else if(month == 7){
                a7++;
            }else if(month == 8){
                a8++;
            }else if(month == 9){
                a9++;
            }else if(month == 10){
                a10++;
            }else if(month == 11){
                a11++;
            }else if(month == 12){
                a12++;
            }
        }
        for(int i=1; i<=12;i++) {
            Map map = new HashMap();
            map.put("name", i + "月");
            if(i==1){
                map.put("value",a1);
            }else if (i ==2 ){
                map.put("value",a2);
            }else if (i ==3 ){
                map.put("value",a3);
            }else if (i ==4 ){
                map.put("value",a4);
            }else if (i ==5 ){
                map.put("value",a5);
            }else if (i ==6 ){
                map.put("value",a6);
            }else if (i ==7 ){
                map.put("value",a7);
            }else if (i ==8 ){
                map.put("value",a8);
            }else if (i ==9 ){
                map.put("value",a9);
            }else if (i ==10 ){
                map.put("value",a10);
            }else if (i ==11 ){
                map.put("value",a11);
            }else if (i ==12 ){
                map.put("value",a12);
            }
            list.add(map);
        }
        return list;
    }

    @Override
    @Transactional
    public int missOrder(String studentPhone, String teacherPhone, String transactionId, String outTradeNo,Integer classTime,BigDecimal totalPrice,BigDecimal price) {
        Integer a = dao.findUserIdByPhone(studentPhone);
        if(a == null){
            return -1;
        }
        Integer b = dao.findUserIdByPhone(teacherPhone);
        if(b == null){
            return -1;
        }
        //第一步
        String result = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date().getTime());
        String[] split = result.split("-");
        String split1="";
        for (String s : split) {
            split1+=s;
        }
        int as = (int)((Math.random()*9+1)*1000);
        String uuid = "DD"+split1+as;
        //补订单
        MissOrderInfo missOrderInfo = new MissOrderInfo();
        missOrderInfo.setClassTime(classTime);
        missOrderInfo.setOutTradeNo(outTradeNo);
        missOrderInfo.setPrice(price);
        missOrderInfo.setStdId(a);
        missOrderInfo.setTeaId(b);
        missOrderInfo.setTotalPrice(totalPrice);
        missOrderInfo.setTransactionId(transactionId);
        missOrderInfo.setUuid(uuid);
        String pay = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date().getTime());
        missOrderInfo.setPayTime(pay);
        int count = dao.insertRecord(missOrderInfo);
        if(count > 0){
            //补小订单
            for(int x=1; x<=classTime;x++){
                String ke = x+"课时";
                count = orderDao.addSmallOrders(missOrderInfo.getId(),ke,missOrderInfo.getPrice());
                if(count < 1){
                    throw new InsertException("新增失败");
                }
            }
            //补家长流水
            String iduu = UUIDUtil.get32UUID();
            count = dao.insertBill(a,iduu,totalPrice,2,"购买课程");
            if(count > 0){
                //增加老师金额
                count = dao.updateUserMoney1(b,totalPrice);
                if(count > 0){
                    //增加老师流水
                    iduu = UUIDUtil.get32UUID();
                    count = dao.insertBill(b,iduu,totalPrice,1,"课程结算");
                    if(count > 0){
                        return 1;
                    }else{
                        throw new InsertException("新增流水失败");
                    }
                }else{
                    throw new UpdateException("修改金额失败");
                }
            }else{
                throw new InsertException("新增流水失败");
            }
        }else{
            throw new InsertException("新增失败");
        }
    }

}
